import { Component, OnInit, Input, OnDestroy, ElementRef, HostListener } from '@angular/core';
import { LayerItem } from '../../data_model/data-model'
import { OlMapService } from '../../services/ol-map.service'
import { DataTransmissionService } from '../../services/data-transmission.service'
import { ModelContainerService } from '../../services/model-container.service'
import { GeoJsonLayer, GeoData } from '../../data_model/data-model'
import { ToastsManager } from 'ng2-toastr/ng2-toastr';
import { WindowEventService } from '../../services/window.event.service'
@Component({
  selector: 'app-layer-list',
  templateUrl: './layer-list.component.html',
  styleUrls: ['./layer-list.component.css'],
  providers: [OlMapService]
})

export class LayerListComponent implements OnInit {

  private SelectedLayerItemId: string;
  private LayerItems: Array<LayerItem> = [];
  private layerShowing = false;
  private LayersListHeight: number;
  constructor(private olMapService: OlMapService,
    private dataTransmissionService: DataTransmissionService,
    private modelContainerService: ModelContainerService,
    private toastr: ToastsManager,
    private windowEventService: WindowEventService) {

  }
  ngOnInit() {
    //每次添加数据都会执行
    this.dataTransmissionService.getFile().subscribe(file => {
      this.LayerItems.push(new LayerItem(file.name.substr(0, file.name.lastIndexOf('.')), true, file));
    })

    //准备接收外部的获取layer list的请求
    this.dataTransmissionService.getReqAllLayerData().subscribe(next => {
      this.dataTransmissionService.sendLayerListSubject(this.LayerItems);
    })

    //
    //轮询结果的返回
    this.dataTransmissionService.getModelRunRecord().subscribe(next => {

      let JsonObject = JSON.parse(JSON.parse(next._body).data);
      if (JsonObject &&
        JsonObject.data &&
        JsonObject.data.msr_output &&
        JsonObject.data.msr_output[0] &&
        JsonObject.data.msr_output[0].DataId &&
        JsonObject.data.msr_output[0].Event) {
        console.log('show data ' + JsonObject.data.msr_output[0].Event + ' .');
        this.dataTransmissionService.sendRemoteData(new GeoData(JsonObject.data.msr_output[0].Event,
          '',
          0,
          JsonObject.data.msr_output[0].DataId));
      }

    }, error => {
      console.log(error);
    })

    this.dataTransmissionService.getRemoteData().subscribe(data => {
      this.LayerItems.push(new LayerItem(data.name, false, null, data.id));
      this.toastr.success("Calculation completed.", "SUCCESS");
    })

    this.LayersListHeight = window.outerHeight;
    this.windowEventService.getWindowResizeSubject().subscribe(next => {
      this.LayersListHeight = next.outerHeight - 20;
    })

    // this.dataTransmissionService.getMapResizeSubject().subscribe( next=>{
    //     this.LayersListHeight = ((parseFloat(next.outerWidth)-47.5)/1.97)+ 'px';
    // })
  }



  onLayerItemClick(DataId: string) {
    this.SelectedLayerItemId = DataId;

  }
  //显示、隐藏图层
  onEyeClicked(layerItem: LayerItem, e: Event) {
    let currentItem = this.LayerItems.find((value) => value.dataId === layerItem.dataId);

    //如果不可见
    if (!currentItem.visible) {


      if (currentItem.layerShowing === true) {
        return;
      }
      currentItem.layerShowing = true;

      //如果是本地数据
      if (currentItem.isLocal) {
        // //还未加载到OlMap
        if (!currentItem.uploaded) {

          this.olMapService.getGeoJsonByFile(currentItem.file).then(data => {

            currentItem.visible = !layerItem.visible;
            currentItem.uploaded = true;
            //传给olMap
            this.dataTransmissionService.sendGeoJson(new GeoJsonLayer(currentItem.dataId, JSON.parse(data._body).data));
            currentItem.layerShowing = false;
          }, reason => {
            console.log(reason);
            currentItem.layerShowing = false;
          })
        } else {
          //已经加载到olMap上，直接设置layer的visible属性
          currentItem.visible = !layerItem.visible;
          this.dataTransmissionService.sendLayerId(currentItem.dataId);
          currentItem.layerShowing = false;
        }
      } else {
        //还未加载到OlMap
        if (!currentItem.uploaded) {

          //如果不是本地，从模型服务容器请求数据并转回json
          this.modelContainerService.getGeoJson(currentItem.dataId).then(data => {
            currentItem.visible = !layerItem.visible;
            currentItem.uploaded = true;
            //传给olMap
            this.dataTransmissionService.sendGeoJson(new GeoJsonLayer(currentItem.dataId, JSON.parse(data._body).data));
            currentItem.layerShowing = false;
          }).catch(reason => {
            currentItem.layerShowing = false;
            console.log(reason);
          })
        } else {

          //已经加载到olMap上，直接设置layer的visible属性
          currentItem.visible = !layerItem.visible;
          this.dataTransmissionService.sendLayerId(currentItem.dataId);
          currentItem.layerShowing = false;
        }
      }
    } else {
      this.dataTransmissionService.sendLayerId(currentItem.dataId);
      currentItem.visible = !layerItem.visible;

    }


    e.stopPropagation();
  }

  //////////按键事件/////////
  @HostListener('document:keyup', ['$event'])
  onkeydown(event: KeyboardEvent) {
    if (event.keyCode === 46) {
      //删除选中的item
      if (this.SelectedLayerItemId) {
        let findedItem = this.LayerItems.find((value) => value.dataId === this.SelectedLayerItemId);
        if (findedItem) {
          this.dataTransmissionService.sendDeleteLayerSubject(this.SelectedLayerItemId);
          this.LayerItems.splice(this.LayerItems.indexOf(findedItem), 1);
        }
      }
    }
  }

  //////////处理函数/////////

}
